package com.itic.mall.mobile.users.coupon;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.omg.PortableInterceptor.USER_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.syssetting.persistence.model.SysSetting;
import com.itic.appbase.applications.sys.syssetting.service.SysSettingService;
import com.itic.appbase.framework.type.CouponState;
import com.itic.appbase.framework.type.CouponType;
import com.itic.appbase.framework.type.SysSettingType;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.goods.skucoupon.persistence.model.SkuCoupon;
import com.itic.mall.system.goods.skucoupon.service.SkuCouponService;
import com.itic.mall.system.project.coupon.persistence.model.ProjectCoupon;
import com.itic.mall.system.project.coupon.service.ProjectCouponService;
import com.itic.mall.system.users.usercoupon.persistence.model.UsersCoupon;
import com.itic.mall.system.users.usercoupon.service.UsersCouponService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.sun.star.lib.connections.socket.socketAcceptor;

@Controller
@RequestMapping(value="/mobile/coupon")
public class UsersCouponInterface extends BaseMobileInterface{
	
	@Autowired
	private ProjectCouponService projectCouponService;
	@Autowired
	private SkuCouponService skuCouponService;
	@Autowired
	private GoodsSpuService goodsSpuService;
	@Autowired
	private UsersCouponService UsersCouponService;
	@Autowired
	private SysSettingService SysSettingService;
	

	
	@RequestMapping("receive")
	@ResponseBody
	public Map<String, Object> receiveCoupon(HttpServletResponse response,String token ,String appId,String couponId,int type){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			CouponState couponState = null;
			if(StringUtils.isNoneBlank(token,appId,couponId) &&(couponState = CouponState.getCouponState(type))!=null) {
				//验证优惠券库存是否有 是否失效
				UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall !=null) {
					int count =0;
					boolean flag = true;
					switch (couponState) {
						case sys:
							String [] couponIds = couponId.split(",");
							for(String coupon:couponIds) {
								ProjectCoupon projectCoupon =  this.projectCouponService.getExpireTime(coupon);
								if(projectCoupon != null){
									count = projectCoupon.getCount()==null?0:projectCoupon.getCount();
									if(count<=0 && count !=-1){
										flag = false;
										break;
									}
								}
								else {
									flag = false;
									break;
								}
							}
							break; 
						case goods:
							SkuCoupon skuCoupon =  this.skuCouponService.getSkuCouponExpireTime(couponId);
							if(skuCoupon != null)
								count = skuCoupon.getTotalCount()==null?0:skuCoupon.getTotalCount();
							else 
								flag = false;
							
							break;
					}
					if(flag && (count==-1 || count>0)) {
						List<UsersCoupon> usersCoupons = this.usersCouponService.getUserCouponByUserIdAndCouponId(usersMall.getId(),couponId);
						//判断是否领取过优惠券  添加优惠券
						if(usersCoupons.isEmpty()) {
							switch (couponState) {
								case sys:
									// 添加优惠券
									String [] couponIds = couponId.split(",");
									for(String coupon:couponIds) {
										ProjectCoupon projectCoupon =  this.projectCouponService.get(coupon);
										this.usersCouponService.addUsersCoupon(projectCoupon.getStartTime(), projectCoupon.getEndTime(), projectCoupon.getId(), usersMall.getId(), projectCoupon.getName(),projectCoupon.getType(), null, projectCoupon.getAmount(),projectCoupon.getUseCond(),couponState);
										int total = projectCoupon.getCount();
										total--;
										projectCoupon.setCount(total);
										this.projectCouponService.edit(projectCoupon);
									}
									break;
								case goods:
									SkuCoupon skuCoupon =  this.skuCouponService.get(couponId);
									this.usersCouponService.addUsersCoupon(skuCoupon.getStartTime(), skuCoupon.getEndTime(),skuCoupon.getId(), usersMall.getId(), skuCoupon.getName(), skuCoupon.getType(), skuCoupon.getSpuId(), skuCoupon.getMoney(), skuCoupon.getLimitFullMoney(),couponState);
									break;
							}
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}else {
							// 提示已经领过优惠券
							errorCode = AlREADY_RECEIVE_COUPON_ERROR_CODE;
							errorMsg = AlREADY_RECEIVE_COUPON_ERROR_MSG;
						}
					}else {
						// 优惠券失效
						errorCode = COUPON_EXPIRETIME_ERROR_CODE;
						errorMsg = COUPON_EXPIRETIME_ERROR_MSG;
					}
				}else {
					// 提示登录失效
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("UsersCouponInterface", "receiveCoupon", e.toString(), "领取优惠券", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	@RequestMapping(value="info")
	@ResponseBody
	public Map<String, Object> couponInfo(HttpServletResponse response ,String token ,String appId,String goodsId,int type){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			CouponState couponState = null;
			if((couponState = CouponState.getCouponState(type))!=null) {
				String couponId="";
				Map<String, Object> dataMap = new HashMap<>();
				GoodsSpu goodsSpu = goodsSpuService.get(goodsId);
				Map<String, Object> goodMap = new HashMap<>();
				goodMap.put("goodName",goodsSpu.getGoodsName());
				goodMap.put("mainImg", goodsSpu.getMainImageUrl());
				goodMap.put("totalSales", goodsSpu.getTotalSales());
				goodMap.put("price", goodsSpu.getPrice());
				goodMap.put("conPrice", goodsSpu.getConPrice());
				dataMap.put("goodInfo", goodMap);
				switch (couponState) {
					case sys:
						
						break;
					case goods:
						SkuCoupon skuCoupon = this.skuCouponService.getSkuCouponByGoodId(goodsId);
						if(skuCoupon!=null){
							dataMap.put("price", skuCoupon.getMoney());
							DateHelper.parseDate(skuCoupon.getStartTime());
							dataMap.put("startTime",DateHelper.formatDate(skuCoupon.getStartTime()));
							dataMap.put("endTime",DateHelper.formatDate( skuCoupon.getEndTime()));
							dataMap.put("id", skuCoupon.getId());
							couponId=skuCoupon.getId();
						}
						
						
					default:
						break;
				}
				if(StringUtils.isNoneBlank(appId,token)){
					UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
					if(usersMall !=null){
						if(StringUtils.isNotEmpty(couponId)){
							UsersCoupon usersCoupon = this.usersCouponService.getUsersCouponByCouponId(couponId);
							List<UsersCoupon> usersCoupons = this.usersCouponService.getUserCouponByUserIdAndCouponId(usersMall.getId(),couponId);
							int state = usersCoupons.isEmpty()?0:1;
							dataMap.put("state", state);
						}else{
							dataMap.put("state", 2);
						}
					}else
						dataMap.put("state", 3);
				}else
					dataMap.put("state", 3);
				resultMap.put(DATA, dataMap);
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
				
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("UsersCouponInterface", "couponInfo", e.toString(), "优惠券详情页面", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	@RequestMapping(value="user/list")
	@ResponseBody
	public Map<String, Object> getUserCouponList(HttpServletResponse response ,String token,String appId,int type){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			CouponState couponState = null;
			if(StringUtils.isNoneBlank(token,appId) && (couponState = CouponState.getCouponState(type))!=null) {
				UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall !=null) {
					//获取用户未过期的优惠券
					List<UsersCoupon> usersCoupons = this.usersCouponService.getUsersCouponByUserId(usersMall.getId(),couponState,"1");
					List<Map<String, Object>> couponList = new ArrayList<>();
					for(UsersCoupon coupon : usersCoupons) {
						Map<String, Object>  couponMap = new HashMap<>();
						couponMap.put("id", coupon.getCouponId());
						couponMap.put("name", coupon.getCouponName());
						couponList.add(couponMap);
					}
					resultMap.put(DATA, couponList);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
				}else{
					// 提示登录失效
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("UsersCouponInterface", "getUserCouponList", e.toString(), "个人优惠券列表", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	@RequestMapping(value="sys/list")
	@ResponseBody
	public Map<String, Object> sysCouponList(HttpServletRequest request,HttpServletResponse response,String token,String appId){

		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			String Value = this.sysSettingService.getByKey(SysSettingType.IS_OPEN_SYS_COUPON.toString());
			if("1".equals(Value)) {
				UsersMall usersMall = null;
				List<ProjectCoupon> projectCoupons = new ArrayList<>();
				if(StringUtils.isNoneBlank(appId,token))
					usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall!=null)
					projectCoupons = this.projectCouponService.getAlertSySCoupon(usersMall.getId());
				else
					projectCoupons = this.projectCouponService.getAlertSySCoupon("aaaaa");
				List<Map<String, Object>> list = new ArrayList<>();
				if(!projectCoupons.isEmpty()) {
					for(ProjectCoupon coupon : projectCoupons) {
						Map<String, Object> map = new HashMap<>();
						map.put("price", coupon.getAmount());
						map.put("id", coupon.getId());
						map.put("useCond", coupon.getUseCond());
						CouponType couponType = CouponType.getCouponType(coupon.getType());
						String typeName = couponType!=null?couponType.getName():"满减券";
						map.put("name", typeName);
						list.add(map);
					}
					dataMap.put("couponBg", projectCoupons.get(0).getImagePath());
				}
				dataMap.put("list", list);
			}
			dataMap.put("isOpen", Value);
			resultMap.put(DATA, dataMap);
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("UsersCouponInterface", "sysCouponList", e.toString(), "系统优惠券列表", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
}
